package com.fsc.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fsc.entity.domain.ChildSituation;
import com.fsc.mapper.ChildSituationMapper;
import com.fsc.service.ChildSituationService;
import com.fsc.util.OssUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.time.LocalDate;
import java.util.List;
import java.util.UUID;

@Service
public class ChildSituationServiceImpl extends ServiceImpl<ChildSituationMapper, ChildSituation> implements ChildSituationService {

    @Autowired
    private ChildSituationMapper childSituationMapper;

    private static final String endpoint = "oss-cn-guangzhou.aliyuncs.com";
    private static final String bucketName = "su-bucket666";

    @Override
    public List<ChildSituation> getVideosByClassId(int classId) {
        return childSituationMapper.getVideosByClassId(classId);
    }

    @Override
    public void uploadVideo(int classId, MultipartFile file, String time) throws IOException {
        String fileName = generateUniqueFileName(file.getOriginalFilename());
        OssUtil.uploadImage(file.getBytes(), fileName);

        ChildSituation childSituation = new ChildSituation();
        childSituation.setClassId(classId);
        childSituation.setTime(LocalDate.parse(time));
        childSituation.setVideoUrl(fileName);

        childSituationMapper.insert(childSituation);
    }

    private String generateUniqueFileName(String originalFilename) {
        String uuid = UUID.randomUUID().toString().replaceAll("-", "");
        return "video/" + uuid + originalFilename;
    }

    @Override
    public void addChildSituation(ChildSituation childSituation) {
        childSituationMapper.insert(childSituation.getClassId(), childSituation.getVideoUrl(), childSituation.getTime().toString());
    }

    @Override
    public void deleteChildSituation(Integer id) {
        childSituationMapper.deleteById(id);
    }


    @Override
    public void updateVideo(Integer id, Integer classId, MultipartFile file, String time) throws IOException {
        ChildSituation childSituation = childSituationMapper.selectById(id);
        if (childSituation == null) {
            throw new IllegalArgumentException("Invalid video id");
        }

        if (classId != null) {
            childSituation.setClassId(classId);
        }

        if (time != null) {
            childSituation.setTime(LocalDate.parse(time));
        }

        if (file != null) {
            String fileName = generateUniqueFileName(file.getOriginalFilename());
            OssUtil.uploadImage(file.getBytes(), fileName);
            childSituation.setVideoUrl(fileName);
        }

        childSituationMapper.updateById(childSituation);
    }
}
